<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :search.sync="query"
      ref="crud"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot-scope="{ row }" slot="menu">
        <!--        <el-button type="text" size="small" icon="el-icon-view" @click="handleView(row, 'view')">详情</el-button>-->
        <el-button type="text" size="small" icon="el-icon-edit" @click="handleEdit(row, 'edit')">处理</el-button>
        <el-button type="text" size="small" @click="handleAddOverdueDate(row)">追加期限</el-button>
        <el-button type="text" size="small" @click="handleScrap(row)">报废</el-button>
        <el-button type="text" size="small" v-if="permission.qcWaitInspectionSheet_executeInspection" @click="handleExecuteInspection(row)">执行检验</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
    </avue-crud>
    <el-dialog append-to-body title="报废" :visible.sync="scrapVisible" width="30%" @close="closeScrapModel">
      <avue-form ref="scrapForm" v-model="scrapModel" :option="scrapOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="scrapSubmit"><i class="el-icon-delete"></i><span>提 交</span></el-button>
        <el-button size="small" @click="scrapVisible = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>

    <el-dialog append-to-body title="追加期限" :visible.sync="addOverdueVisible" width="30%" @close="closeAddOverdueModel">
      <avue-form ref="addOverdue" v-model="addOverdueModel" :option="addOverdueOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="addOverdueSubmit"><i class="el-icon-delete"></i><span>提 交</span></el-button>
        <el-button size="small" @click="addOverdueVisible = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <handle-over-time-wait-inspect ref="handleInspect" :visible.sync="handleVisable" @closeDialog="handleCloseBeforeInspect"></handle-over-time-wait-inspect>
  </basic-container>
</template>

<script>
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { getAddOption } from '@/views/quality/refactor/shipmentWaitInspect';
import { getList } from '@/api/quality/beforePackingWaitInspect';
import handleOverTimeWaitInspect from '@/views/quality/handleOverTimeWaitInspect';
import { addOverdueDate, scrapMaterial } from '@/api/quality/incomingMaterialsToBeInspected';
import executeInspection from '@/views/designer/preview';
import { mapGetters } from 'vuex';
export default {
  name: 'overTimeWaitInspect',
  mixins: [userConfig()],
  components: {
    userTableConfig,
    handleOverTimeWaitInspect,
    commonModalTemplate,
    executeInspection
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  created() {
    let queryParams = this.$route.query;
    if (queryParams && queryParams.partNo) {
      this.query.partNo = decodeURIComponent(queryParams.partNo);
    }
  },
  data() {
    return {
      executeInspectionDialog: false,
      rowData: {},
      scrapModel: {},
      scrapVisible: false,
      scrapOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 110,
        column: [
          {
            label: '报废原因',
            prop: 'remark',
            span: 24,
            type: 'textarea',
            maxlength: 50,
            showWordLimit: true,
            rules: [
              {
                required: true,
                message: '请输入报废原因',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      addOverdueVisible: false,
      addOverdueModel: {},
      addOverdueOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 130,
        column: [
          {
            label: '追加保质期天数',
            prop: 'addDeadline',
            span: 24,
            type: 'number',
            rules: [
              {
                required: true,
                message: '请输入追加保质期天数',
                trigger: 'blur'
              },
              {
                validator: this.validatePositiveInteger,
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      option: {
        height: 'calc(100vh - 480px)',
        calcHeight: 30,
        selectionList: [],
        tip: false,
        searchShow: true,
        searchMenuSpan: 5,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        indexLabel: '序号',
        columnBtn: false,
        selection: true,
        menuWidth: 260,
        column: [
          {
            label: '检验单号',
            prop: 'documentNo',
            searchOrder: 5,
            search: true
          },
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'partName',
            search: true
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '物料批次',
            prop: 'lotNo'
          },
          {
            label: '物料数量',
            prop: 'sendExamineQuantity'
          },
          {
            label: '报检时间',
            prop: 'sendExamineDate'
          },
          {
            label: '超期次数',
            prop: 'partOverdueCount'
          }
        ]
      },
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      sheetHeaderVo: [],
      exportParams: {},
      handleVisable: false,
      selectionList: [],
      data: [],
      form: {},
      query: {}
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {};
    }
  },
  methods: {
    exeInspectionCloseDialog() {
      this.executeInspectionDialog = false;
      this.onLoad(this.page);
    },
    handleExecuteInspection(row) {
      if (!row.apaasTemplateId) {
        this.$message({
          type: 'warning',
          message: `${row.partNo}（物料编码）没有配置检验模板，请先进行配置！`
        });
        return;
      }
      this.executeInspectionDialog = true;
      this.$nextTick(() => {
        this.$refs.executeInspection.viewApaasTemplate(row.apaasTemplateId);
      });
    },
    async onLoad(page, params = {}) {
      try {
        this.loading = true;
        const baseParams = { documentType: 'ODQC' };
        const res = await getList(page.currentPage, page.pageSize, Object.assign(params, this.query, baseParams));
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      } catch (e) {
      } finally {
        this.loading = false;
      }
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    selectionChange(list) {
      this.selectionList = list;
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    handleEdit(row, type) {
      this.$refs.handleInspect.getData(row.id);
      this.handleVisable = true;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    handleCloseBeforeInspect() {
      this.onLoad(this.page);
    },
    validatePositiveInteger(rule, value, callback) {
      if (Number.isInteger(Number(value)) && Number(value) > 0) {
        callback();
      } else {
        callback(new Error('请输入正整数！'));
      }
    },
    handleScrap(row) {
      this.rowData = row;
      this.scrapVisible = true;
    },
    handleAddOverdueDate(row) {
      this.rowData = row;
      this.addOverdueVisible = true;
    },
    closeScrapModel() {
      this.$refs.scrapForm.resetForm();
    },
    closeAddOverdueModel() {
      this.$refs.addOverdue.resetForm();
    },
    addOverdueSubmit(form, done) {
      this.$refs.addOverdue.validate(async (valid, done) => {
        if (valid) {
          this.$confirm('填写此天数后，物料依然到达保质期预警提前天数，物料将自动生成新的待检单，是否确认追加此天数？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            const data = {
              partNo: this.rowData.partNo,
              lotNo: this.rowData.lotNo,
              productDateStr: this.rowData.partProductionDate,
              addDeadline: this.addOverdueModel.addDeadline
            };
            await addOverdueDate(data);
            this.$message.success('追加期限成功');
            this.addOverdueVisible = false;
            this.$emit('update:visible', false);
            this.$emit('closeDialog');
            this.addOverdueModel = {};
          });
        }
        done();
      });
    },
    scrapSubmit(form, done) {
      this.$refs.scrapForm.validate(async (valid, done) => {
        if (valid) {
          this.$confirm('物料报废后不可撤回，是否确认报废?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            const data = {
              partNo: this.rowData.partNo,
              lotNo: this.rowData.lotNo,
              productDateStr: this.rowData.partProductionDate,
              remark: this.scrapModel.remark
            };
            await scrapMaterial(data);
            this.$message.success('报废成功');
            this.scrapVisible = false;
            this.$emit('update:visible', false);
            this.$emit('closeDialog');
            this.scrapModel = {};
          });
        }
        done();
      });
    }
  }
};
</script>

<style scoped></style>
